package com.zxl.yunpicture.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxl.yunpicture.application.service.PictureApplicationService;
import com.zxl.yunpicture.application.service.SpaceApplicationService;
import com.zxl.yunpicture.application.service.SpaceUserApplicationService;
import com.zxl.yunpicture.application.service.UserApplicationService;
import com.zxl.yunpicture.domain.space.entity.Space;
import com.zxl.yunpicture.domain.space.entity.SpaceUser;
import com.zxl.yunpicture.domain.space.service.SpaceDomainService;
import com.zxl.yunpicture.domain.space.valueObject.SpaceLevelEnum;
import com.zxl.yunpicture.domain.space.valueObject.SpaceRoleEnum;
import com.zxl.yunpicture.domain.space.valueObject.SpaceTypeEnum;
import com.zxl.yunpicture.domain.user.entity.User;
import com.zxl.yunpicture.infrastructure.common.DeleteRequest;
import com.zxl.yunpicture.infrastructure.exception.BusinessException;
import com.zxl.yunpicture.infrastructure.exception.ErrorCode;
import com.zxl.yunpicture.infrastructure.exception.ThrowUtils;
import com.zxl.yunpicture.infrastructure.mapper.SpaceMapper;
import com.zxl.yunpicture.interfaces.dto.space.SpaceAddRequest;
import com.zxl.yunpicture.interfaces.dto.space.SpaceQueryRequest;
import com.zxl.yunpicture.interfaces.vo.picture.PictureVO;
import com.zxl.yunpicture.interfaces.vo.space.SpaceVO;
import com.zxl.yunpicture.interfaces.vo.user.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author ZhangXL
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-02-26 17:52:23
*/
@Service
public class SpaceApplicationServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceApplicationService {

    @Resource
    private @Lazy PictureApplicationService pictureApplicationService;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private SpaceUserApplicationService spaceUserApplicationService;

    @Resource
    private SpaceDomainService spaceDomainService;




    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        //对象转封装类
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        //关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0){
            User user = userApplicationService.getUserById(userId);
            UserVO userVO = userApplicationService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userApplicationService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userApplicationService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        return spaceDomainService.getQueryWrapper(spaceQueryRequest);
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        spaceDomainService.fillSpaceBySpaceLevel(space);
    }

    @Override
    public void deleteSpace(DeleteRequest deleteRequest, HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        Long id = deleteRequest.getId();
        //判断是否存在
        Space oldSpace = this.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        //仅本人或管理员可以删除
        this.checkSpaceAuth(loginUser,oldSpace);
        //加事务
        transactionTemplate.execute(status -> {
            //操作数据库
            boolean result = this.removeById(id);
            ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"删除失败");
            //删除空间也要同步删除空间中的图片
            //根据spaceId查询全部私人空间的图片
            List<PictureVO> pictureLists = pictureApplicationService.getPictureListsBySpaceId(id);
            //批量删除 todo
            for (PictureVO pictureVO : pictureLists){
                pictureApplicationService.deletePicture(pictureVO.getId(),loginUser);
            }

            return true;
        });
    }

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        //先转换dto和实体类
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest,space);
        //默认值
        if (StringUtils.isBlank(spaceAddRequest.getSpaceName())){
            space.setSpaceName("默认空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (spaceAddRequest.getSpaceType() == null){
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        //填充数据
        this.fillSpaceBySpaceLevel(space);
        //数据校验
        space.validSpace(true);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        //权限校验
        if (SpaceLevelEnum.COMMON.getValue() != spaceAddRequest.getSpaceLevel() && !loginUser.isAdmin()){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权限创建指定级别的空间");
        }
        //针对用户加锁 控制同一个用户只能创建一个私有空间
        String lock = String.valueOf(userId).intern();
        synchronized (lock){
            Long newSpaceId = transactionTemplate.execute(status -> {
                //从space表中拿到用户信息 如果有，说明该用户已经创建过私有空间了
                boolean exists = this.lambdaQuery().
                        eq(Space::getUserId, userId).
                        eq(Space::getSpaceType, space.getSpaceType()).
                        exists();
                ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每个用户每类空间只能创建一个");
                //写入数据库
                boolean result = this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                // 如果是团队空间，关联新增团队成员记录
                if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequest.getSpaceType()) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    result = spaceUserApplicationService.save(spaceUser);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                }
                //创建分表 (仅对团队空间生效)
                //dynamicShardingManager.createSpacePictureTable(space);
                //返回新写入的数据id
                return space.getId();
            });
            return newSpaceId;
        }
    }

    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        spaceDomainService.checkSpaceAuth(loginUser,space);
    }

}




